package com.dmagic.cms.controller;

import java.util.List;
import java.util.Map;

import jodd.util.StringUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dmagic.cms.common.controller.CommonController;
import com.dmagic.cms.common.util.JsonUtil;
import com.dmagic.cms.entity.Language;
import com.dmagic.cms.entity.ProductCategory;
import com.dmagic.cms.service.BaseService;
import com.dmagic.cms.service.ProductCategoryService;

@Controller
@RequestMapping(value = "/category")
public class ProductCategoryController extends CommonController {

	private String PRODUCT_CATEGORY = "category/productCategory";

	private String PRODUCT_CATEGORY2 = "category/productCategory2";

	private String SUCCESSFUL_CASE_CATEGORY = "category/successfulCaseCategory";
	static {

	}

	@Autowired
	private BaseService baseService;

	@Autowired
	private ProductCategoryService productCategoryService;

	@RequestMapping
	public String category(Model model, @RequestParam String type) {
		List<Language> languages = baseService.getAllLanguages();
		model.addAttribute("language", languages);
		model.addAttribute("defaultForm", languages.get(0).getLanguageKey());
		if (StringUtil.equals("product", type)) {
			return PRODUCT_CATEGORY2;
		} else {
			return SUCCESSFUL_CASE_CATEGORY;
		}
	}

	@RequestMapping("save")
	@ResponseBody
	public String saveCategory(@RequestParam String category) {
		List<Map> categorys = JsonUtil.fromJson(category, List.class);
		productCategoryService.saveCategory(categorys);
		return "Successful";
	}

	@RequestMapping("save2")
	@ResponseBody
	public String saveCategory2(@RequestParam String category) {
		List<Map> categorys = JsonUtil.fromJson(category, List.class);
		productCategoryService.saveCategory2(categorys);
		return "Successful";
	}

	@RequestMapping(value = "getAll", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getCategory() {
		List<ProductCategory> list = productCategoryService.getAllParentCategory();
		return JsonUtil.toFullJson(list);
	}

	@RequestMapping("delete")
	@ResponseBody
	public String deleteCategory(@RequestParam Long categoryId) throws Exception {
		if (categoryId != null)
			productCategoryService.deleteCategory(categoryId);
		return "Delete Successful.";
	}
}
